package controller;

import model.Player;
import model.PlayersData;
import model.Table;
import view.*;

public class GameSetUp {
	public static final int TABLE_SIZE = 15;
	public static final int NUMBER_OF_PLAYERS = 2;
	GetGameInfo getGameInf = new GetGameInfo();
	Table gameTable;
	PlayersData pd;

	public void setUpGame() {
		createTable(TABLE_SIZE);
		createPlayers(NUMBER_OF_PLAYERS);
		setUpPlayersInfo();
		showAll();
		fillArray();
	}

	private void createTable(int tableSize) {
		gameTable = new Table(tableSize);
	}

	private void createPlayers(int numOfPlayers) {
		pd = new PlayersData();
	}

	private void setUpPlayersInfo() {
		String name;
		char mark;
		for (int index = 0; index < pd.getPlayers().length; index++) {
			do {
				name = getGameInf.getPlayersName(index);
			} while (!nameIsFree(name));
			do {
				mark = getGameInf.getPlayersMark(index);
			} while (!markIsFree(mark));
			pd.addPlayer(new Player(name, mark), index);
		}
	}

	private boolean nameIsFree(String name) {
		for (Player p : pd.getPlayers()) {
			if (p == null)
				break;
			if (p.getName().equals(name))
				return false;
		}
		return true;
	}

	private boolean markIsFree(char mark) {
		for (Player p : pd.getPlayers()) {
			if (p == null)
				break;
			if (p.getMark() == mark)
				return false;
		}
		return true;
	}

	private void showAll() {
		for (int index = 0; index < GameSetUp.NUMBER_OF_PLAYERS; index++) {
			playerOrComputer(index);
		}
	}

	private void playerOrComputer(int index) {
		if (index == 0) {
			System.out.println("Player name:" + pd.getPlayers()[index].getName());
			System.out.println("Player mark:" + pd.getPlayers()[index].getMark());
			System.out.println();
		} else {
			System.out.println("Computer name:" + pd.getPlayers()[index].getName());
			System.out.println("Computer mark:" + pd.getPlayers()[index].getMark());
			System.out.println();
		}
	}

	private void fillArray() {
		for (int row = 0; row < GameSetUp.TABLE_SIZE; row++) {
			for (int col = 0; col <  GameSetUp.TABLE_SIZE; col++) {
				Table.updateArray(row, col, ' ');
			}
		}
	}
}